/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package verins.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import verins.beans.Imgpadron;
import verins.beans.Personarnvxprocesoelectoral;
import verins.beans.Procesoelectoral;
import verins.beans.Procesoempadronamiento;
import verins.beans.Rol;

/**
 *
 * @author hectdx
 */
public class IOmethods {
    
     public static byte[] convertFileToByte(String pathImagen){

        File fileImagen = new File(pathImagen);
        byte[] bFile = new byte[(int) fileImagen.length()];

        try {
            FileInputStream fileInputStream = new FileInputStream(fileImagen);
            fileInputStream.read(bFile);
            fileInputStream.close();
            return bFile;
        } catch (Exception e) {
            return null;
        }
    }

     
     public static byte [] getPadronImgFromBD(int padron, int procesoelectoral){
     byte[] bFile = null;
     Conexion con=new Conexion();   
         PreparedStatement pstmt=null;
         ResultSet rset=null;
         String sSQl="";
         try{
             sSQl="select  padron from verinscribe.imgpadron  "+
                   "where idimgpadron=? and idproceso=? ";
             
             pstmt=con.getConexion().prepareStatement(sSQl);
             
             pstmt.setInt(1,padron);
             pstmt.setInt(2,procesoelectoral);
        
             rset=pstmt.executeQuery();
             
             if (rset.next()){
                 bFile=rset.getBytes(1);
             }
             
             
         }catch(Exception e){
             System.out.println("Error al grabar padron "+ e.getMessage());
         }finally{
             try{
                 pstmt.close();
                 rset.close();
             }catch(Exception e){}
         }
     return bFile;
     }

     public static boolean guardarFirmante(Personarnvxprocesoelectoral persona)throws Exception{
         boolean bOK=false;
         Conexion con=new Conexion();
         PreparedStatement pstmt=null;

         String sSQl="";
         try{
             sSQl="insert into verinscribe.Personarnvxprocesoelectoral (personarnv,procesoelectoral,padronelectoral,pagina) "+
                   "values (?,?,?)";
             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.setInt(1,persona.getPersonarnvxprocesoelectoralPK().getPersonarnv());
             pstmt.setInt(2,persona.getPersonarnvxprocesoelectoralPK().getProcesoelectoral());
             pstmt.setString(3,persona.getPadronelectoral());
             pstmt.setInt(4,persona.getPagina());
             pstmt.executeUpdate();

             con.getConexion().commit();
             con.getConexion().close();
             System.out.println("...insert");
         }catch(SQLException e){
              return false;
         }
             bOK=true;

         return bOK;
     }

     
     public static boolean vaciarPermisos(Rol rol){
        boolean bOK=false;
         try{
             Conexion con=new Conexion();
             PreparedStatement pstmt=null;

             String sSQl="";

             sSQl= "DELETE FROM verinscribe.permisoxrol " +
                    "WHERE idrol="+rol.getIdrol()+";";


             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.executeUpdate();

             con.getConexion().commit();
             con.getConexion().close();
             System.out.println("...delete");
         }catch(SQLException e){
              return false;
         }
         bOK=true;
         return bOK;
     }


     public static boolean verificaInscripcion(Procesoelectoral ele, Procesoempadronamiento emp)throws Exception{
         boolean bOK=false;
         try{
             Conexion con=new Conexion();
             PreparedStatement pstmt=null;

             String sSQl="";

             sSQl= "UPDATE verinscribe.partidopoliticoxprocesoelectoral " +
                    "SET estadoinscrip = '" + verins.Utils.Constantes.INSCRITO + "', fechainscrip = current_date " +
                    "WHERE idprocesoelectoral = "+ele.getIdprocesoelectoral().toString()+" AND idpartidopolitico in " +
                        "(SELECT pe.idpartidopolitico " +
                        "FROM verinscribe.actaprocesamiento ap, verinscribe.partidopoliticoxprocesoelectoral pe, verinscribe.padronelectoral pad " +
                        "WHERE pe.idprocesoelectoral = "+ele.getIdprocesoelectoral().toString()+" AND pe.idpartidopolitico=pad.idpartidopolitico AND pad.idpadronelectoral=ap.idpadronelectoral " +
                        "GROUP BY pe.idpartidopolitico " +
                        "HAVING sum(ap.numeroregistrosvalidos) > "+emp.getIndiceminimofirmas()+");";


             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.executeUpdate();

             con.getConexion().commit();
             con.getConexion().close();
             System.out.println("...update");
         }catch(SQLException e){
              return false;
         }
         bOK=true;
         return bOK;
     }

     public static boolean cargarPadron(Imgpadron padron)throws Exception{
         boolean bOK=false;
         Conexion con=new Conexion();   
         PreparedStatement pstmt=null;
         
         String sSQl="";
         try{
             sSQl="insert into verinscribe.imgpadron (idimgpadron,idproceso,padron) "+
                   "values (?,?,?)";
             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.setInt(1,padron.getIdimgpadron());
             pstmt.setInt(2,padron.getIdproceso());
             pstmt.setBytes(3, padron.getPadron());
             pstmt.executeUpdate();
             
             con.getConexion().commit();
             con.getConexion().close();
             System.out.println("...insert");
         }catch(SQLException e){
              sSQl="update verinscribe.imgpadron set padron=? "+
                   "where idimgpadron=? and idproceso= ?";
             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.setBytes(1, padron.getPadron());
             pstmt.setInt(2,padron.getIdimgpadron());
             pstmt.setInt(3,padron.getIdproceso());
             
             pstmt.executeUpdate();
             
             con.getConexion().commit();
             con.getConexion().close();
            System.out.println("...update");
         }
             bOK=true;
            
         return bOK;
     }
     
     
      public static boolean cargarFirmaRNV(byte [] img, String dni)throws Exception{
         boolean bOK=false;
         Connection con=new Conexion().getConexion();   
         PreparedStatement pstmt=null;
         
         String sSQl="";
         try{
              sSQl="update verinscribe.personarnv set firma=? "+
                   "where dni=? ";
             pstmt=con.prepareStatement(sSQl);
             pstmt.setBytes(1, img);
             pstmt.setString(2,dni);
             
             
             pstmt.executeUpdate();
             
             con.commit();
             con.close();
           
         }catch(SQLException e){
             
         }
             bOK=true;
            
         return bOK;
     }
      
      public static boolean cargarHuellaRNV(byte [] img, String dni)throws Exception{
         boolean bOK=false;
         Conexion con=new Conexion();   
         PreparedStatement pstmt=null;
         
         String sSQl="";
         try{
              sSQl="update verinscribe.personarnv set huella=? "+
                   "where dni=? ";
             pstmt=con.getConexion().prepareStatement(sSQl);
             pstmt.setBytes(1, img);
             pstmt.setString(2,dni);
             pstmt.executeUpdate();
             
             con.getConexion().commit();
             con.getConexion().close();
           
         }catch(SQLException e){
             System.out.println(e.getMessage());
         }
             bOK=true;
            
         return bOK;
     }
      
      public static String getRealPath(){
          File directory = new File ("x");
          String ruta="";
             try {
               ruta=directory.getCanonicalPath();
               ruta=ruta.substring(0, ruta.length()-1);
               int i=ruta.indexOf("/dist");
               if (i>-1){
                   ruta=ruta.replace("/dist", "");
               }
               System.out.println("n:"+ruta);
               return ruta;
               
             }catch(Exception e) {
             System.out.println("Exceptione is ="+e.getMessage());
             return "/";
             }
    }
     
      public static boolean guardarConexion(String strConex){
          boolean bok=false;
          String[] strData=null;
          try{
              System.out.println(strConex);
              strData=strConex.split(",");
              String server=strData[0];
              String user=strData[1];
              String pass=strData[2]; 
              
              String pathConex=getRealPath()+"/conn";
               
              File fc =new File(pathConex);
              FileWriter fw=new FileWriter(fc);
              fw.write(strConex);
              fw.close();
              
              Conexion con=new Conexion();
             
              
              Conexion.strConex=server;
              Conexion.pass=pass;
              Conexion.user=user;
              con.getConexion();
              return true;       
              
          }catch(Exception e){
              System.out.println(e.getMessage());
          }

          return bok;
              
      }
     
      
      
      
      public static void main(String arg []){
        System.out.println("ini main");
         
        try{
            /*
           String ruta=Comunes.getPathImagenes()+"padron.JPG";
           Imgpadron padron=new Imgpadron(1);
           padron.setIdproceso(11);
           byte[] f=convertFileToByte(ruta);
           cargarHuellaRNV(f, "45110226");
           f=convertFileToByte(ruta);
           cargarFirmaRNV(f, "45110226");
           
           //byte [] bd=getPadronImgFromBD(padron.getIdimgpadron(), padron.getIdproceso());
           //System.out.println(bd.length);
           //Comunes.enviarEmail("hector_oliv_dfrst@hotmail.com", "mail", "<p>monkey</p>");
           BigInteger bi=new BigInteger("FFD8FFE000104A46494600010100000100010000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720222C231C1C2837292C30313434341F27393D38323C2E333432FFDB0043010909090C0B0C180D0D1832211C213232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232FFC0001108004800EB03012200021101031101FFC4001F0000010501010101010100000000000000000102030405060708090A0BFFC400B5100002010303020403050504040000017D01020300041105122131410613516107227114328191A1082342B1C11552D1F02433627282090A161718191A25262728292A3435363738393A434445464748494A535455565758595A636465666768696A737475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFC4001F0100030101010101010101010000000000000102030405060708090A0BFFC400B51100020102040403040705040400010277000102031104052131061241510761711322328108144291A1B1C109233352F0156272D10A162434E125F11718191A262728292A35363738393A434445464748494A535455565758595A636465666768696A737475767778797A82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2F3F4F5F6F7F8F9FAFFDA000C03010002110311003F00F7EA28A299214514500145145001451450014668A4FC280168A4A5A0028A2827140051505C5DC76A631264798DB4103F9D4F9CD03B05145140828A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0028A28A0029334B55A7955BF708EA246E3AF205034AE456FA8ADCDF4B02AFCA8321F3D69D3DD798EB6F6EC0C8DD587F08F5A8EDA254D426080048E3541F8F3557489163B59EE652373CACA38E78270299562DC109B7BFD8B23B2B47960C73CD5E1D2A85A2CA2569C9C898E71FDDF6ABE0E6864B42D55B89A4F3161800F30F527F84558C83C020FAE29A1312B37A8033484665FDAB6C803CCF2399475E9F956B018AA3700CBA95BA76452E7F4AB30CEB3193683846DB9F5A6CAE84B4B54C6A76CD746DC392C3B81F2FE752A4921B9746036601522913627A2AADE5C98226083326D27E94FB37796D22793EF32E4D0327A28A281051451400514514005145140051451400514514005145140051451400D7FBA79C71D6B3E1B149E2F36641E61CED6EE2ADC8C5E55897A0E5CFB7A53E4C242D8E801C531A7628E9C2510CEC7E666725589EA3A62A1D16D98DA89262090EC428E80E4D695B27976D1AFB5476313C36E51D403BD881ED9A2E36C5B26325B86E9927F9D5449986EB589B33339273CED5F5AB5623CB80C47EF231CFE26A61046B319820121182DEB40AFA9950E2DF509D21259CA8400FAF735674C4994DCB4CE5B32719AB22DE389A59517F78FC93EB4B6A852D914F5EF45CA6CA7325C1D49BCB5F95E30BBFD3D69B77662DA05789DC22C81D941EA3BD6A5215C8C1C11DF228B8AE519A6856D563859497C0455F5A591A7B79D5844D22B205F97B35588ED6089B74712A9F502A6C5170B946E4325936EE647C2B60D5C41B5428EC314D9625990A37434F031409B168A28A420A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A280102E33EF4150460F4A5A2800031451450018A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2800A28A2803FFFD900",16);
                                         
        System.out.println(bi);
        byte [] a=bi.toByteArray();
         padron.setPadron(a);
        cargarPadron(padron);
            
         
           byte [] bd=getPadronImgFromBD(padron.getIdimgpadron(), padron.getIdproceso());
           bi=new BigInteger(bd);
           
           String s = bi.toString(16);
           System.out.println(s);
          
           Image img=new ImageIcon(bd).getImage();
            
         */
            String strconex="jdbc:postgresql://quilla.lab.inf.pucp.edu.pe:1042/postgres,postgres,victoria";
            guardarConexion(strconex);
           
           
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        System.out.println("fin main");
    }

}
